A Web API Operations In ASP.NET Core
To get along with this article, you need to have SQL Server and Visual Studio (we used Visual Studio 2019) installed on your system.
Here is how you do it:
- Open Visual Studio 2019.
- In the Visual Studio 2019 welcome screen that launches, select Create a new project from the options shown on the right.
- In the following screen, select ASP.NET Core Web Application.
- Click Next.
- There is the New ASP.NET Core Web Application window that will open next. Select the Web Application (Model-View-Controller) option here.
- Select the Configure for HTTPS checkbox at the bottom.
- Click OK.
- In the Configure your new project window that opens, enter a project name.
- Click on the Create button.
- In the Solution Explorer window, create a new folder and name it Models.
- Thereafter, in the Models folder, create a new class and name it Employees.
public class Employees { [Key] public int ID { get; set; } public string Name { get; set; } public string Email { get; set; } }
Add an interface to the Models class and name it IDataRepository
. Add the following code.
public interface IDataRepository<TEntity> { IEnumerable<TEntity> GetAll(); TEntity Get(int id); void Add(TEntity entity); void Change(TEntity dbEntity, TEntity entity); void Delete(TEntity entity); }
Adding an interface is necessary for implementing Generic Repository as this would allow for defining generic functions. Overall, five methods are being declared for CRUD operations. The methods will then be implemented in the action class of each model.
Next, add an Action class. Add a class and name it EmployeesManager
. Add the following code in the EmployeesManager
class.
public class EmployeesManager : IDataRepository<Employees> { readonly DbContext dbContext; public EmployeesManager(DbContext context) { dbContext = context; } public IEnumerable<Employees> GetAll() { return dbContext.Employees.ToList(); } public EmployeeGet(int id) { return dbContext.Employees .FirstOrDefault(e => e.ID == id); } public void Add(Employees employees) { dbContext.Employees.Add(employees); dbContext.SaveChanges(); } public void Change(Employees employees, Employees entity) { employees.Name = entity.Name; employees.Email = entity.Email; dbContext.SaveChanges(); } public void Delete(Employees employees) { dbContext.Employees.Remove(employees); dbContext.SaveChanges(); } }
As is evident from the code above, the IDataRepository
interface inherits the EmployeesManager
class. Also, all the methods that have been defined in IDataRepository
interface get implemented in this class for CRUD operations.
Next, add a new class and name it DbContext
and add the following code to the class.
public class DbContext { public DbContext(DbContextOptions<DbContext> options) : base(options) { } public DbSet<Employees> Employees { get; set; } }
Add the following connection string in your appsetting.json
file.
{ "Logging": { "Loglevel": { "Default": "Warning" } }, "ConnectionString": { "tDB": "server= xyz; database=Database;integrated security = true;" }, "AllowedHosts": "*" }
Next for implementing the CRUD operation, you will have to add a Controller for Employees Class. For this, add a New Controller and name it EmployeesController
. Add the following code in EmployeesController
.
public class EmployeesController : Controller { private IDataRepository<Employees> _repository; public EmployeesController(IDataRepository<Employees> repository) { _repository = repository; } // GET: api/<controller> [HttpGet] public IActionResult Get() { IEnumerable<Employees> employees = _repository.GetAll(); return Ok(employees); } // GET api/<controller>/5 [HttpGet("{id}")] public IActionResult Get(int id) { Employees employees = _repository.Get(id); if (employees == null) { return NotFound("The Employee record couldn't be found."); } return Ok(employees); } // POST api/<controller> [HttpPost] public IActionResult Post([FromBody]Employees employee) { if (employee == null) { return BadRequest("Employee is Null"); } _repository.Add(employee); return CreatedAtRoute("Get", new { Id = employee.ID }, employee); } // PUT api/<controller>/5 [HttpPut("{id}")] public IActionResult Put(int id, [FromBody]Employees employee) { if (employee == null) { return BadRequest("Employee is null"); } Employees employeeToUpdate = _repository.Get(id); if (employeeToUpdate == null) { return NotFound("Employee could not be found"); } _repository.Change(employeeToUpdate, employee); return NoContent(); } // DELETE api/<controller>/5 [HttpDelete("{id}")] public IActionResult Delete(int id) { Employees employee = _repository.Get(id); if (employee == null) { return BadRequest("Employee is not found"); } _repository.Delete(employee); return NoContent(); } }
Implement the CRUD operations
The process starts by creating a Web API:
For that, create a new project in Visual Studio and it a name, say CRUD_operation.
In the next window that opens, select the Web API template.
Click OK.
In Solution Explorer, add a new API Controller and the name is EmployeesController.
Create a new SQL table and name is Employees.
Next, add an ADO.NET Entity Data Model for your database.
Finally, you will also be required to create an ‘Entities‘ class object in EmployeesController, the new API controller you just created.
Now for the actual CRUD operations:
For the READ operation:
There are two GET
methods to accomplish the same, the code snippets for which is added below.
This method does not accept any parameters and returns a list of all employees.
public IEnumerable<Employees> Get() { return db.Employees.ToList(); }
This method accepts an ID as a parameter and will return the only record that matches that ID.
public EmployeeGet(int id) { Employees employees = db.Employees.Find(id); return employee; }
For Create operation:
This is accomplished by the POST
method in API. In the POST method shown here, the method will accept an Employee as a parameter and will add the same in the database as a new record.
public void POST(Employees employee ) { db.Employees.Add(employee); db.SaveChanges(); }
For Update operation:
This is accomplished by the PUT
method and will accept a parameter to update the details that match with that parameter, which generally is the ID related to that employee.
public void PUT(int id, Employees employee) { var emp = db.Employees.Find(id); emp.Email = employee.Name; emp.FullName = employee.Email; db.Entry(emp).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); }
For Delete operation:
This again is accomplished by the method of the same name, .i.e. is the DELETE method. Also, the method takes an ID as a parameter and will delete the record that matches that parameter.
public string Delete(int id) { Employees employee = db.Employees.Find(id); db.Employees.Remove(employee); db.SaveChanges(); return "Employee Deleted"; }
Conclusion:
So, this should serve as a guide to understanding the concept of generic repository and CRUD operations in ASP.NET Core
using Web API
.
Comments